package com.lagou.edu.service.impl;

import com.lagou.edu.dao.User;
import com.lagou.edu.mapper.ITokenMapper;
import com.lagou.edu.mapper.IUserMapper;
import com.lagou.edu.service.ICodeService;
import com.lagou.edu.service.IUserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Description TODO
 * @Classname IUserServerImpl
 * @Date 2021/5/30 16:46
 * @Author ch'ien
 */

@Service
public class IUserServerImpl implements IUserService {

    @Autowired
    private IUserMapper userMapper;

    @Autowired
    private ITokenMapper tokenMapper;

    @Reference
    private ICodeService codeClient;

    @Override
    public int register(String email, String password, String code) {

        int validate = codeClient.validate(email, code);
        if (validate != 0){
            return validate;
        }
        userMapper.save(email, password);

        return 0;
    }

    @Override
    public String login(String email, String password, HttpServletResponse response) {
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password) ){
            return "";
        }
        User byEmailAndPassWord = userMapper.getByEmailAndPassWord(email, password);
        if (byEmailAndPassWord == null){
            return "";
        }

        String token = UUID.randomUUID().toString();
        Cookie cookie = new Cookie("token",token);
        cookie.setPath("/");
        tokenMapper.save(email, token);

        response.addCookie(cookie);
        return byEmailAndPassWord.getEmail();
    }

    @Override
    public boolean isRegistered(String email) {

        return userMapper.isRegistered(email) > 0;
    }

    @Override
    public String info(String token) {

        return tokenMapper.getOne(token);
    }

    @Override
    public String testMsg() throws InterruptedException {
        Thread.sleep(500);
        return codeClient.testMsg();
    }
}
